<?php
class Acl_User_Role
{
    const _CONST_CACHE_KEY_      = 'ur_';
    const _CONST_DEFAULT_ROLE_   = 'member';
    const _CONST_ROLE_GUEST_     = 'guest';
    const _CONST_TB_USERROLE_    = 'user_user_role';
    const _CONST_TB_ROLE_	     = 'user_role_define';

    protected $_cache;

    public function __construct ()
    {
        $this->_cache = Cache::instance();
    }

    // @param	int	user id
    // @return	object	implements of RoleInterface
    public function get_default_role ($uid)
    {
        $key = self::_CONST_CACHE_KEY_ . $uid;
        $role_name = $this->_cache->get($key);
		$user_id   = User::current_user_id();

        if (empty($role_name))
        {
            $role_name = $this->get_default_rolename ($uid);
            $this->_cache->set($key, $role_name, Kohana::config('acl_config.timeout.user_role'));
        }

        return Acl_Role_Mgr::factory($role_name, $user_id);
    }

    // ['member', 'info', 'train']
    protected function get_default_rolename ($uid)
    {
        if (empty($uid))
            return self::_CONST_ROLE_GUEST_;

        $query = DB::select('role_name')
                 ->from(self::_CONST_TB_USERROLE_)
                 ->join(self::_CONST_TB_ROLE_ , 'LEFT')
				 ->on(self::_CONST_TB_USERROLE_. '.role', '=', self::_CONST_TB_ROLE_ .'.id')
                 ->where(self::_CONST_TB_USERROLE_.'.uid', '=', $uid)
                 ->limit(1);

        $result = $query->execute();

        if ($result->count() > 0)
        {
			return $result->get('role_name');
        }
        else
            return self::_CONST_DEFAULT_ROLE_;
    }
}
